package grame

import grails.util.Metadata
import org.junit.Test

import javax.servlet.ServletContext

/**
 * @author Shining Wang <shiningwang@topca.com>
 */
class AppUpgrade {
    static void run(ServletContext servletContext){
        //系统当前版本信息
        def appVer = Metadata.getCurrent().getApplicationVersion(); //application.properties default 1.0
        AppSetting versionSetting = AppSetting.findByName("app.version");
        def dataVersion = new AppVersion(versionSetting.value)
        def appVersion = new AppVersion(appVer)
        if (appVersion <= dataVersion)
            return

        println "Current application version is $dataVersion"
        def versionsToRun = []
        def scriptDir = new File(servletContext.getRealPath("/WEB-INF/upgrade/"))
        scriptDir.eachFile {
            it.name.find(/^upgrade.([\d\.]+)\.groovy/) { m, version ->
                version = new AppVersion(version as String)
                if (version > dataVersion)
                    versionsToRun << version
            }
        }
        versionsToRun.sort().each {
            println("Upgrading to version $it...")
            def scriptFile = new File(scriptDir, "upgrade.${it}.groovy")
            Script script = (Script) new GroovyClassLoader().parseClass(scriptFile).newInstance()
            script.binding = new Binding([
                    ant: new AntBuilder(),
                    servletContext: servletContext.getRealPath("/"),
            ])
            script.run()
            versionSetting.value = it.toString()
            versionSetting.save()
        }

        versionSetting.value = appVersion
        versionSetting.save()
        println("Upgraded to version $appVersion")
    }

    @Test
    void testUpgrade() {
        Metadata.getCurrent().setProperty(Metadata.APPLICATION_VERSION as String, "1.0.0")
        def context = [
                getRealPath: { path -> return new File("web-app$path").absolutePath },
        ]
        AppSetting.metaClass.static.findByName = { String n -> new AppSetting(name: "app.version", value: "1.0") }
        AppSetting.metaClass.static.executeQuery = {}
        AppSetting.metaClass.static.executeUpdate = {}
        AppSetting.metaClass.save = {}

        run(context as ServletContext)
    }
}
